package edu.vt.ece4564.bluetendance.classes;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import edu.vt.ece4564.bluetendance.database.DatabaseConnector;
import edu.vt.ece4564.bluetendance.students.Student;

public class ClassInfoGetter implements Runnable {

	private HttpServletResponse response;
	private int classID;

	public ClassInfoGetter(HttpServletResponse response, int classID) {
		this.response = response;
		this.classID = classID;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void run() {
		DatabaseConnector dc = DatabaseConnector.get();
		
		dc.commandText = "call SP_GetClassInfo(" + classID + ");";
		ResultSet classInfoResults = dc.executeQuery();
		
		Class newClass = null;
		
		try {
			while (classInfoResults.next()) {
				newClass = new Class(classID, classInfoResults.getString("ClassName"), classInfoResults.getString("TeacherName"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		dc.commandText = "call SP_GetClassMembers(" + classID + ");";
		ResultSet results = dc.executeQuery();

		List<Student> listOfStudents = new ArrayList<Student>();

		try {
			while (results.next()) {
				listOfStudents.add(new Student(results.getInt("StudentID"), results.getString("StudentName")));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		newClass.setStudentsList(listOfStudents);

		response.setContentType("application/plain");

		PrintWriter out = null;
		
		try {
			out = response.getWriter();
		}
		catch (IOException e) {
			e.printStackTrace();
		}

		if (listOfStudents.size() > 0) {
			JSONArray array = new JSONArray();
			JSONObject obj = new JSONObject();
			obj.put("ClassID", newClass.getClassID());
			obj.put("ClassName", newClass.getClassName());
			obj.put("TeacherName", newClass.getTeacherName());
			obj.put("NumberOfStudents", newClass.getListOfStudents().size());
			int studentNum = 0;
			for (Student student : newClass.getListOfStudents()) {
				obj.put("StudentID" + studentNum, student.getStudentID());
				obj.put("StudentName" + studentNum, student.getStudentName());
				studentNum++;
			}
			array.add(obj);
			
			StringBuilder sb = new StringBuilder(array.toString());
			if (sb.charAt(0) == '[') {
				sb.deleteCharAt(0);
			}
			if (sb.charAt(sb.length() - 1) == ']') {
				sb.deleteCharAt(sb.length() - 1);
			}
			out.println(sb);
		}
		else {
			JSONObject obj=new JSONObject();

			obj.put("valid","false");
			out.println(obj.toString());
		}
		out.close();
	}
}
